package d2_reflect_test;

import org.junit.Test;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

/**
 * @Author Cjj
 * @Date:2025/5/6
 * 目标：掌握获取类的构造器,并对其进行操作
 */
public class Test2Constructor {
    @Test
    public void testGetConstructor() {
        //1.反射第一步：必须先得到这个类的Class对象
        Class c = Cat.class;
        //2.获取类的全部构造器
        Constructor[] constructors = c.getConstructors();
        //3.遍历数组中的每个构造器对象
        for (Constructor constructor : constructors) {
            System.out.println(constructor.getName() + "--->" + constructor.getParameterCount());
        }
    }
    public void testGetConstructors() throws Exception {
       //1.反射第一步：必须先得到这个类的Class对象
        Class c = Cat.class;

        //2.获取某个构造器：无参数构造器
       Constructor constructor= c.getConstructor();
        System.out.println(constructor.getName() + "--->" + constructor.getParameterCount());

        //3.获取有参数构造器
        Constructor constructor2 = c.getConstructor(String.class, int.class);
        System.out.println(constructor2.getName() + "--->" + constructor2.getParameterCount());
        Cat cat2 =(Cat) constructor2.newInstance("叮当猫", 3);
        System.out.println(cat2);


    }
}
